package com.baozun.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.baozun.model.TFriend;
import com.baozun.model.TFriendExample;
import com.baozun.model.TUser;
import com.baozun.model.TUserExample;
import com.baozun.service.FriendService;
import com.baozun.service.UserService;
import com.baozun.util.AjaxUtil;
import com.baozun.util.CommonConst;
import com.baozun.util.ModelMapUtil;
import com.baozun.util.PageData;
import com.baozun.util.SessionUtil;
import com.baozun.util.StringUtil;
import com.baozun.util.WebUtil;

/**
 * 好友
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Description:
 * @Author:xiaozhou.zhou
 * @Since:2015年1月23日
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:
 * @Version:1.1.0
 */
@Controller
@RequestMapping("/friend")
public class FriendController {
    
    @Autowired
    @Qualifier("friendService")
    private FriendService friendService;
    @Autowired
    private UserService userService;
    
    
    private int pageSize = 20;
    private int currentPage = 1;
    
    /**
     * 进入好友主界面
     * 
     * @return
     * @Description:
     */
    @RequestMapping("/friend_main")
    public String friendMain() {
        return "friend/friend_main";
    }
    
    /**
     * 进入好友列表界面
     * 
     * @param model
     * @param request
     * @return
     * @Description:
     */
    @RequestMapping("/friend_list")
    public String friendList(ModelMap model, HttpServletRequest request) {
        // 根据用户名或昵称搜索用户
        String nameOrRemark = request.getParameter("name_or_remark");
        String pageSizeStr = request.getParameter("pageSize");
        String currentPageStr = request.getParameter("currentPage");
        pageSize = StringUtil.getIntFromStr(pageSizeStr, pageSize);
        currentPage = StringUtil.getIntFromStr(currentPageStr, currentPage);
        // 取出当前登录用户
        TUser user = SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);
        String stUserId = user.getStUserId();
        // 查询好友列表（从friend中查询所有from或to为当前用户ID）
        TFriendExample record = new TFriendExample();
        if (StringUtils.isNotEmpty(nameOrRemark)) {
            // 如果是请求用户
            record.createCriteria().andStUserIdRequestEqualTo(stUserId).andStNameResponseLike("%"+nameOrRemark+"%");
            // 如果是响应用户
            record.or(record.createCriteria().andStUserIdResponseEqualTo(stUserId).andStNameRequestLike("%"+nameOrRemark+"%"));
        }
        record.createCriteria().andStUserIdRequestEqualTo(user.getStUserId());
        record.or(record.createCriteria().andStUserIdResponseEqualTo(user.getStUserId()));
        
        PageData<TFriend> infoList = friendService.getPageListByExample(record, pageSize, currentPage);
        new ModelMapUtil(model).put(CommonConst.REQUEST_PAGE_DATA, infoList).put("pageSize", pageSize).put("currentPage", currentPage);
        return "friend/friend_list";
    }
    
    /**
     * 
     * @param model
     * @param request
     * @return
     * @Description:
     */
    @RequestMapping("/friend_add")
    public String friendAdd(ModelMap model, HttpServletRequest request) {
        TUser user = SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);
        // 查找用户，将还不是好友的用户查询出来
        TUserExample record = new TUserExample();
        List<TUser> userList = userService.getList(record);
        // 得到现在的好友列表
        TFriendExample friendRecord = new TFriendExample();
        // 请求或响应的是当前用户
        friendRecord.createCriteria().andStUserIdRequestEqualTo(user.getStUserId());
        friendRecord.or(friendRecord.createCriteria().andStUserIdResponseEqualTo(user.getStUserId()));
        List<TFriend> friendList = friendService.getList(friendRecord);
        // 根据好友列表生成好友的ID映射
        Map<String, String> friendMap = new HashMap<String, String>();
        for (TFriend friend : friendList) {
            if (friend.getStUserIdRequest().equals(user.getStUserId())) {
                friendMap.put(friend.getStUserIdResponse(), friend.getStUserIdRequest());
            } else {
                friendMap.put(friend.getStUserIdRequest(), friend.getStUserIdResponse());
            }
            
        }
        // 将已经是好友的用户剔除
        Iterator<TUser> userIte = userList.iterator();
        List<TUser> isFriendUser = new ArrayList<TUser>();
        while (userIte.hasNext()) {
            TUser singleUser = userIte.next();
            if (friendMap.containsKey(singleUser.getStUserId())) {
                isFriendUser.add(singleUser);
            }
        }
        userList.removeAll(isFriendUser);
        model.put("userList", userList);
        return "friend/friend_add";
    }
    
    @RequestMapping("/friend_add_submit")
    public String friendAddSubmit(ModelMap model, HttpServletRequest request, @RequestParam("stUserIdResponse") String[] stUserIdResponseArray) {
        TUser user = SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);
        for (String stUserIdResponse : stUserIdResponseArray) {
            // 根据id查到用户
            TUser userResponse = userService.get(stUserIdResponse);
            // 生成好友数据
            TFriend friend = new TFriend();
            friend.setStNameRequest(user.getStName());
            friend.setStUserIdRequest(user.getStUserId());
            friend.setStStatus(CommonConst.BOOLEAN_VALUE_FALSE_STR);
            friend.setStNameResponse(userResponse.getStName());
            friend.setStUserIdResponse(userResponse.getStUserId());
            friendService.add(friend);
        }
        
        new ModelMapUtil(model).put("msg", WebUtil.encodeURL("新增好友成功！")).put("jsm", "workLater");
        return "include/refresh";
    }
    
    /**
     * 好友删除
     * 
     * @param request
     * @param response
     * @param stFriendId
     */
    @RequestMapping("/friend_delete")
    public void friendDelete(HttpServletRequest request, HttpServletResponse response, @RequestParam("stFriendId") String stFriendId) {
        PrintWriter out = AjaxUtil.getWriter(request, response);
        try {
            friendService.delete(stFriendId);
            out.print(CommonConst.AJAX_RIGHT);
        } catch (Exception e) {
            out.print(CommonConst.AJAX_ERROR);
            e.printStackTrace();
        }
    }
    
    /**
     * 备注的修改
     * 
     * @param request
     * @param response
     * @param stFriendId
     * @param stRemark
     */
    @RequestMapping("/friend_remark_update_submit")
    public void friendRemarkUpdateSubmit(HttpServletRequest request, HttpServletResponse response, @RequestParam("stFriendId") String stFriendId, @RequestParam("stRemark") String stRemark) {
        TUser user = SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);
        PrintWriter out = AjaxUtil.getWriter(request, response);
        try {
            TFriend friend = friendService.get(stFriendId);
            if(friend.getStUserIdRequest().equals(user.getStUserId())){
                friend.setStRemarkResponse(stRemark);
            }else{
                friend.setStRemarkRequest(stRemark);
            }
            friendService.update(friend);
            out.print(CommonConst.AJAX_RIGHT);
        } catch (Exception e) {
            out.print(CommonConst.AJAX_ERROR);
            e.printStackTrace();
        }
    }
}
